package com.hh.eduorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.hh.eduorder.entity.Order;
import com.hh.eduorder.entity.PayLog;
import com.hh.eduorder.mapper.OrderMapper;
import com.hh.eduorder.mapper.PayLogMapper;
import com.hh.eduorder.service.PayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.eduorder.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author huhuan
 * @since 2022-02-20
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PayLogMapper payLogMapper;
    
    // 点击去支付生成支付二维码信息
    @Override
    public HashMap<String, Object> createPayOrder(String orderNo) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        Order order = orderMapper.selectOne(wrapper);

        try {
            //1、设置支付参数
            Map paramMap = new HashMap<>();
            paramMap.put("courseId", order.getCourseId());
            paramMap.put("appid", "wx74862e0dfcf69954");
            paramMap.put("mch_id", "1558950191");
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("body", order.getCourseTitle());
            paramMap.put("out_trade_no", orderNo);
            paramMap.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("spbill_create_ip", "192.168.60.120");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            paramMap.put("trade_type", "NATIVE");

            // 2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            httpClient.setHttps(true);
            httpClient.post();

            //3、返回第三方的数据
            String xml = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);

            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("out_trade_no", orderNo);
            resultMap.put("course_id", order.getCourseId());
            resultMap.put("total_fee", order.getTotalFee());
            resultMap.put("result_code", map.get("result_code"));
//            resultMap.put("code_url", map.get("code_url"));
            resultMap.put("code_url", map.get("123"));
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成支付码失败!");
        }
    }

    // 查询支付状态
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        Map<String, String> resultMap;
        try {
            // 1、封装参数
            Map map = new HashMap<>();
            map.put("appid", "wx74862e0dfcf69954");
            map.put("mch_id", "1558950191");
            map.put("out_trade_no", orderNo);
            map.put("nonce_str", WXPayUtil.generateNonceStr());

            // 2、发送请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(map,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            // 3、接收返回对象
            String xml = client.getContent();
            resultMap = WXPayUtil.xmlToMap(xml);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询支付状态失败!");
        }
        return resultMap;
    }

    @Override
    public void updatePayLogStatus(Map paySuccess,Integer success) {
        String orderNo = (String) paySuccess.get("out_trade_no");
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        Order order = orderMapper.selectOne(wrapper);

        if ("1".equals(order.getStatus()) || success == 0) {
            return;
        } else {
            order.setStatus(1);

            // 插入支付记录表
            PayLog payLog = new PayLog();
            payLog.setOrderNo(orderNo);
            payLog.setPayTime(new Date());
            payLog.setTotalFee(order.getTotalFee());
            payLog.setTransactionId((String) paySuccess.get("transaction_id"));
            payLog.setPayType(1);
            payLog.setAttr(JSONObject.toJSONString(paySuccess));
            payLog.setTradeState((String) paySuccess.get("trade_state"));
            payLogMapper.insert(payLog);
            orderMapper.updateById(order);
        }
    }
}
